package com.taptech.doufu.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.NovelRankItemAdapter;
import com.taptech.doufu.ui.adapter.NovelRankMainAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.bean.novel.NovelRankItemSortBean;
import com.taptech.doufu.bean.novel.NovelTyrantBean;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.ui.view.readview.util.ScreenUtils;
import com.taptech.doufu.util.DoufuUtils;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.ItemClickSupport;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.viewholder.personalcenter.MessageViewHolderFactory;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 精选页面排行榜
 */

public class RankFragment extends DiaobaoBaseFragment implements ItemClickSupport.OnItemClickListener, MyRecyclerView.OnScrollToBottomListener, HttpResponseListener {


    public static final String INTENT_KEY_LOAD_DATA_NOW = "intent_key_load_data_now";
    public static final int version = 2;
    private LinearLayout layRankTop;

    /**
     * left item
     */
    private RecyclerView mItemRecyView;
    private List<NovelRankItemSortBean.DataBean.ItemBean> itemBeanList;
    private NovelRankItemAdapter novelRankItemAdapter;
    private List<NovelRankItemSortBean.DataBean.ItemBean.SortBean> sortList;

    /**
     * main list view
     */
    private MyRecyclerView mNovelRankRecy;
    private NovelRankMainAdapter novelRankAdapter;
    private boolean hasMoreContent = true;
    private MessageViewHolderFactory viewHolderFactory;


    private String novelRankUrl = "";
    private String last = "";

    private List<MineAbstractBean> mDataList;

    private boolean isChangeUrl = true;
    private WaitDialog dialog;
    //是否是土豪榜
    private boolean isTyrantRank;

    private String url;
    private boolean isInit;


    public static RankFragment newInstance(String url, boolean loadDataNow) {
        RankFragment fragment = new RankFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(INTENT_KEY_LOAD_DATA_NOW,loadDataNow);
        bundle.putString(Constant.URL, url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_choice_rank, null);
        initView(view);
        initData();
        return view;
    }



    private void rxItemSortData() {
        dialog.show();
        ApiClient.getInstance().getService()
                .getNovelRankItemSort(url)
                .compose(RxJavaHelper.<NovelRankItemSortBean>observeOnMainThread(getActivity()))
                .subscribe(new BaseSubscriber<NovelRankItemSortBean>() {
                    @Override
                    public void onNext(NovelRankItemSortBean novelRankItemSortBean) {
                        super.onNext(novelRankItemSortBean);
                        loadData(novelRankItemSortBean);
                    }
                });
    }

    View headView;
    ImageView ivPicBg;

    private void loadData(NovelRankItemSortBean novelRankItemSortBean) {
        itemBeanList = novelRankItemSortBean.getData().getList();
        novelRankItemAdapter = new NovelRankItemAdapter(itemBeanList);
        mItemRecyView.setAdapter(novelRankItemAdapter);
        if (itemBeanList.get(0) != null) {
            sortList = itemBeanList.get(0).getList();
        }

        if (itemBeanList.get(0).getList().size() < 2) {
            layRankTop.setVisibility(View.GONE);
        } else {
            setNovelRankSortSpinnerAdapter(0);
        }
        NovelRankItemSortBean.DataBean.ItemBean.SortBean bean = itemBeanList.get(0).getList().get(itemBeanList.get(0).getDefaultIndex());
        getNovelRankData(bean.getUrl());
        setHeadView(bean);
    }


    private void setHeadView(final NovelRankItemSortBean.DataBean.ItemBean.SortBean bean) {
        if (bean.getLinks() != null) {
            if(headView==null){
                headView = LayoutInflater.from(getContext()).inflate(R.layout.view_rank_banner_item, null);
                ivPicBg =  headView.findViewById(R.id.ivPicBg);
                ivPicBg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(!TextUtils.isEmpty(bean.getLinks().getBanner_link())){
                            if (bean.getLinks().getBanner_link().contains("/weex/")) {
                                SimpleWeexActivity.startActivity(getContext(),bean.getLinks().getBanner_link());
                            }else{
                                Intent intent = new Intent();
                                intent.setClass(getContext(), BrowseActivity.class);
                                intent.putExtra(Constant.URL, bean.getLinks().getBanner_link());
                                startActivity(intent);
                            }
                        }
                    }
                });
                int width = ScreenUtil.getScreenWidth(getContext())-ScreenUtil.dip2px(getContext(),65);
                int height = ScreenUtil.dip2px(getContext(),46);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
                params.gravity = Gravity.CENTER;
                headView.setLayoutParams(params);
            }
            GlideUtil.displayImage(getActivity(),ivPicBg,bean.getLinks().getBanner_img());
            if (novelRankAdapter.getmHeaderViewList().size()==0) {
                novelRankAdapter.addHeaderView(headView);
            }
        }else{
            if (novelRankAdapter.isHeadViewVisible() && headView!=null){
                novelRankAdapter.removeHeaderView(headView);
            }
        }
    }

    public void initGroupData() {
        if (!isInit) {
            isInit = true;
            rxItemSortData();
        }
    }

    private void initData() {
        if (dialog == null) {
            dialog = new WaitDialog(getContext(), R.style.updateDialog);
        }

        viewHolderFactory = new MessageViewHolderFactory();
        mDataList = new ArrayList<>();
        novelRankAdapter = new NovelRankMainAdapter(getContext(), mDataList);
        mNovelRankRecy.setAdapter(novelRankAdapter);
        Bundle bundle = getArguments();
        url = bundle.getString(Constant.URL);
        boolean loadDataNow = bundle.getBoolean(INTENT_KEY_LOAD_DATA_NOW);
        if (loadDataNow) {
            initGroupData();
        }
    }

    private void initView(View rootView) {
        layRankTop = rootView.findViewById(R.id.layRankTop);
        mItemRecyView =  rootView.findViewById(R.id.novel_rank_sort_recycle);
        mNovelRankRecy =  rootView.findViewById(R.id.novle_rank_main_recy);

        GridLayoutManager mg = new GridLayoutManager(getContext(), 1);
        mItemRecyView.setLayoutManager(mg);
        ItemClickSupport.addTo(mItemRecyView).setOnItemClickListener(this);

        RecyclerView.LayoutManager manager = new LinearLayoutManager(getContext());
        mNovelRankRecy.setLayoutManager(manager);
        mNovelRankRecy.setLoadMoreEnable(true);
        mNovelRankRecy.setOnScrollToBottomListener(this);


    }

    TextView lastSelected = null;

    /**
     * left item click
     *
     * @param recyclerView
     * @param position
     * @param v
     */
    @Override
    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
        if (position == -1) {
            return;
        }
        last = "";
        novelRankItemAdapter.setSelPosition(position);
        novelRankItemAdapter.notifyDataSetChanged();
        if (lastSelected != null && position != 0) {
            lastSelected.setSelected(false);
        } else {

        }

        TextView item_tv = (TextView) v.findViewById(R.id.item_novel_rank_left);
        lastSelected = item_tv;
        item_tv.setSelected(true);

        if ("土豪榜".equals(itemBeanList.get(position).getTitle())) {//// TODO: 16/11/30 土豪榜
             isTyrantRank = true;
        }else {
            isTyrantRank = false;
        }

        if (itemBeanList.size() > position) {
            sortList = itemBeanList.get(position).getList();
            if (sortList.size() > 1) {
                layRankTop.setVisibility(View.VISIBLE);
                setNovelRankSortSpinnerAdapter(position);
            } else {
                layRankTop.setVisibility(View.GONE);
                if (sortList.size() > itemBeanList.get(position).getDefaultIndex()) {
                    NovelRankItemSortBean.DataBean.ItemBean.SortBean bean = sortList.get(itemBeanList.get(position).getDefaultIndex());
                    getNovelRankData(bean.getUrl());
                    setHeadView(bean);
                }
            }
        }
    }

    private void setTextViewColor(TextView textView, boolean isSelect) {
        if (WeMediaApplication.getInstance().isDayNightMode_Night) {
            if (isSelect) {
                textView.setBackgroundResource(R.drawable.cycle_red_night);
                textView.setTextColor(getResources().getColor(R.color.white));
            }else{
                textView.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                textView.setTextColor(getResources().getColor(R.color.text_color_6C788A));
            }
        }else{
            if (isSelect) {
                textView.setBackgroundResource(R.drawable.cycle_red);
                textView.setTextColor(getResources().getColor(R.color.white));
            }else{
                textView.setBackgroundResource(R.drawable.bg_tag_gray);
                textView.setTextColor(getResources().getColor(R.color.text_color_6C788A));
            }
        }
        textView.setPadding(ScreenUtils.dpToPxInt(20f), 0, ScreenUtils.dpToPxInt(20f), 0);
    }

    /**
     * set right spinner adapter
     *
     * @param position
     */
    public void setNovelRankSortSpinnerAdapter(final int position) {
        List<NovelRankItemSortBean.DataBean.ItemBean.SortBean> sortBeans = itemBeanList.get(position).getList();
        layRankTop.removeAllViews();
        for (int i = 0; i < sortBeans.size(); i++) {
            final NovelRankItemSortBean.DataBean.ItemBean.SortBean bean = sortBeans.get(i);
            if (i == 0) {
                getNovelRankData(bean.getUrl());
            }
            TextView textView = new TextView(getContext());
            LinearLayout.LayoutParams  params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,ScreenUtil.dip2px(getContext(),27));
            params.leftMargin = ScreenUtil.dip2px(getActivity(), 8);
            textView.setGravity(Gravity.CENTER);
            textView.setLayoutParams(params);
            setTextViewColor(textView,i == 0);
            final int index = i;
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getNovelRankData(bean.getUrl());
                    setHeadView(bean);
                    for (int j = 0; j < layRankTop.getChildCount(); j++) {
                        TextView childText = (TextView) layRankTop.getChildAt(j);
                        setTextViewColor(childText, j == index);
                    }
                }
            });
            textView.setGravity(Gravity.CENTER);
            textView.setText(sortBeans.get(i).getName());
            layRankTop.addView(textView);
        }

    }


    public void getNovelRankData(String url) {
        dialog.show();
        // 初始化变量
        novelRankUrl = url;
        mDataList.clear();
        hasMoreContent = false;
        isChangeUrl = true;
        novelRankAdapter.pullComplete(false);
        HomeMainServices.getInstance().loadAlbumsList(RankFragment.this, novelRankUrl, "");
    }

    /**
     * main novel rank list load more data
     */
    @Override
    public void loadMore() {
        if (hasMoreContent) {
            hasMoreContent = false;
            HomeMainServices.getInstance().loadAlbumsList(RankFragment.this, novelRankUrl, last);
            isChangeUrl = false;
        }
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (response == null) {
            DoufuUtils.netWorkErrorToast(getContext());
            return;
        }
        switch (handleType) {
            case HomeMainServices.HANDLE_TYPE_LOAD_ALBUMS:
                dialog.dismiss();
                JSONObject data = (JSONObject) response.getData();
                if (data == null) {
                    return;
                }
                try {
                    List<? extends MineAbstractBean> dataList = null;
                    if (data.has("items")) {
                        dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("items"));
                    }  else if(isTyrantRank && data.has("list") && data.get("list") instanceof JSONArray){
                        dataList =  com.alibaba.fastjson.JSONArray.parseArray(data.getJSONArray("list").toString(),NovelTyrantBean.class);
                    }else {
                        if ((data.has("list")) && (viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("list")) != null)) {
                            dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("list"));
                        } else if ((data.has("novels")) && (viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("novels")) != null)) {
                            dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("novels"));
                        }
                    }

                    if (isChangeUrl || (dataList != null && data.has("last") && !data.getString("last").equals(last))) {
                        for (int i = 0; i < dataList.size(); i++) {
                            dataList.get(i).setRank_flag(true);
                        }
                        hasMoreContent = true;
                        mDataList.addAll(dataList);
                        novelRankAdapter.notifyDataSetChanged();
                    } else {
                        hasMoreContent = false;
                        novelRankAdapter.pullComplete(true);
                    }
                    if (data.has("last")) {
                        last = data.getString("last");
                    }
                } catch (Exception e) {
                    UIUtil.toastMessage(getContext(), Constant.loadingFail);
                }
                if (lastSelected == null) {
                    lastSelected = (TextView) mItemRecyView.getLayoutManager().findViewByPosition(0).findViewById(R.id.item_novel_rank_left);
                    lastSelected.setSelected(true);
                }
                break;
        }
    }



}
